package com.theexceptions.todo.controller;

import java.util.ArrayList;
import java.util.List;

import com.theexceptions.todo.model.CategoryFilter;
import com.theexceptions.todo.model.CompletedFilter;
import com.theexceptions.todo.model.DatabaseHelper;
import com.theexceptions.todo.model.DateFilter;
import com.theexceptions.todo.model.IPersister;
import com.theexceptions.todo.model.Task;
import com.theexceptions.todo.model.TaskFilter;

/**
 * A controller that handles displaying tasks. This class is to be used by both
 * TasksActivity AND TaskFilterActivity.
 * 
 * @author Justian Meyer
 */
public class TasksController extends Controller {

	private static List<TaskFilter> filters = new ArrayList<TaskFilter>();

	/**
	 * Adds a CategoryFilter to the filter list.
	 * 
	 * @param category Raw data from spinner
	 */
	public static void addCategoryFilter(String category) {
		if (!category.equals("Any"))
			filters.add(new CategoryFilter(category));
	}

	/**
	 * Adds a CompletedFilter to the filter list.
	 * 
	 * @param completed Raw data from spinner
	 */
	public static void addCompletedFilter(String completed) {
		if (completed.equals("Completed"))
			addFilter(new CompletedFilter(true));
		else if (completed.equals("Not Completed"))
			addFilter(new CompletedFilter(false));
	}

	/**
	 * Adds a DateFilter to the filter list.
	 * 
	 * @param time
	 */
	public static void addDateFilter(long time) {
		addFilter(new DateFilter(time));
	}

	/**
	 * Adds a TaskFilter to the filter list.
	 * 
	 * @param filter
	 */
	private static void addFilter(TaskFilter filter) {
		filters.add(filter);
	}

	/**
	 * Clears the filter list.
	 */
	public static void clearFilters() {
		filters.clear();
	}

	/**
	 * Returns an array of the current user's tasks to be displayed in a list
	 * using the provided filters.
	 */
	public static Task[] getCurrentUserTasks() {
		IPersister dh = new DatabaseHelper(context);
		long userID = currentUser.getUserID();

		List<Task> tasksList = dh.retrieveTasksWithFilters(userID, filters);

		Task[] tasksArray = new Task[tasksList.size()];
		for (int i = 0; i < tasksList.size(); i++) {
			tasksArray[i] = tasksList.get(i);
		}

		return tasksArray;
	}

	/**
	 * Toggles whether a task has been completed or not
	 * 
	 * @param task
	 * @return Task's new "completed" state.
	 */
	public static boolean toggleTaskCompleted(Task task) {
		IPersister dh = new DatabaseHelper(context);
		return dh.toggleTaskCompleted(task);
	}

}
